package com.mall.order.mq.promo;

import com.alibaba.fastjson.JSON;
import com.mall.order.OrderPromoService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.dto.CreateSeckillOrderRequest;
import com.mall.order.dto.CreateSeckillOrderResponse;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListener;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @Description: 消费事务消息
 * @Author: 徐能雄
 * @Date: 2021/10/7 21:45
 */
@Component
public class CreatePromoOrderConsumer {

    private DefaultMQPushConsumer consumer;

    @Autowired
    private OrderPromoService orderPromoService;

    @PostConstruct
    public void init() {
        consumer = new DefaultMQPushConsumer("create_promo_order_consumer");
        consumer.setNamesrvAddr("127.0.0.1:9876");
        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {

                try {
                    MessageExt message = list.get(0);
                    byte[] body = message.getBody();
                    String requestStr = new String(body, 0, body.length, "utf-8");

                    CreateSeckillOrderRequest request = JSON.parseObject(requestStr, CreateSeckillOrderRequest.class);

                    //调用下单方法
                    CreateSeckillOrderResponse promoOrder = orderPromoService.createPromoOrder(request);

                    //根据promoOrder判断是否消费成功
                    if (OrderRetCode.SUCCESS.getCode().equals(promoOrder.getCode())) {
                        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                    }

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        });

        try {
            consumer.subscribe("create_promo_order", "*");
            consumer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }


    }
}
